package app.android.kdictionary.Activity;

import java.util.ArrayList;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.RemoteException;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import app.android.kdictionary.R;
import app.android.kdictionary.R.id;
import app.android.kdictionary.Component.SearchSelectRadioDialog;
import app.android.kdictionary.adapter.WebAdapter;
import app.android.kdictionary.aidl.SearchResultData;
import app.android.kdictionary.aidl.SearchServiceConnection;
import app.android.kdictionary.aidl.WebViewContent;
import app.android.kdictionary.data.RefInt;
import app.android.kdictionary.enums.OtherType;
import app.android.kdictionary.enums.SearchResultType;
import app.android.kdictionary.service.SearchService;

public class OtherActivity extends DefaultActivity {
	private ListView listView;
	private ImageView titleImageView;
	private EditText editText;
	private Button selectButton;
	private ImageButton searchButton;
	private ImageButton helpButton;
	
	private OtherType type;
	private RefInt selectItem;
	private String search_select_list[];
	
	private final int RADIO_DIALOG = 0;
	
	private WebAdapter mAdapter;
	
	private BackGroundThread backGroundThread;
	
	private SearchServiceConnection serviceConnection = null;
	
	private SharedPreferences sharedPreferences;
	private SharedPreferences.Editor sharedEditor;
	
	private String metaString = "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">";
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.other);
        
		findView();
		setListener();
		init();
    }
    
	// Dialog 생성
	@Override
    protected Dialog onCreateDialog(int id) {
		switch(id) {
			case RADIO_DIALOG : 
				return new SearchSelectRadioDialog(this, search_select_list, selectItem, selectButton).create();
        }
        return null;
    }
    
    private void findView() {
    	titleImageView = (ImageView)findViewById(id.title_01_ImageView);
    	editText = (EditText)findViewById(id.search_edit);
    	selectButton = (Button)findViewById(id.search_select_button);
    	selectButton.setVisibility(View.VISIBLE);
    	searchButton = (ImageButton)findViewById(id.search_button);
    	listView = (ListView)findViewById(id.search_result_list);
    	listView = (ListView)findViewById(id.search_result_list);
//    	helpButton = (ImageButton)findViewById(id.main_specify_help_button);
    }
    
    private void setListener() {
    	selectButton.setOnClickListener(mSearchSelectClickListener);
    	searchButton.setOnClickListener(mSearchClickListener);
		listView.setOnItemClickListener(mItemClickListener);
//		helpButton.setOnClickListener(mHelpClickListener);
    }
    
    private void init() {
    	sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
    	sharedEditor = sharedPreferences.edit();
    	
    	Intent intent = new Intent(OtherActivity.this, SearchService.class);
    	serviceConnection = new SearchServiceConnection();
        bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);
        
        mAdapter = new WebAdapter(getLayoutInflater());
        listView.setAdapter(mAdapter);
        
    	type = OtherType.valueOf(sharedPreferences.getString("type",""));
    	
        Resources mRs = getResources();
        switch(type) {
    		case IDIOM : // 관용
    			titleImageView.setBackgroundDrawable(mRs.getDrawable(R.drawable.headline5));
    			search_select_list = mRs.getStringArray(R.array.search_select_list_0);
    			break;
    			
        	case ADAGE : // 속담
        		titleImageView.setBackgroundDrawable(mRs.getDrawable(R.drawable.headline6));
        		search_select_list = mRs.getStringArray(R.array.search_select_list_0);
        		break;
        		
        	case DIALECT : // 방언 
        		titleImageView.setBackgroundDrawable(mRs.getDrawable(R.drawable.headline7));
        		search_select_list = mRs.getStringArray(R.array.search_select_list_1);
        		break;
        		
        	case NKOREA : // 북한어
        		titleImageView.setBackgroundDrawable(mRs.getDrawable(R.drawable.headline8));
        		search_select_list = mRs.getStringArray(R.array.search_select_list_1);
        		break;
        		
        	case NATIVE : // 고유어
        		titleImageView.setBackgroundDrawable(mRs.getDrawable(R.drawable.headline9));
        		search_select_list = mRs.getStringArray(R.array.search_select_list_1);
        		break;
        }
        
    	selectItem = new RefInt(0);
    	selectButton.setText(search_select_list[selectItem.getValue()]);
    }
    
    private OnClickListener mSearchClickListener = new OnClickListener() {
        public void onClick(View v) {
			// keyboard remove
			InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE); 
    		imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);

			// adapter clear
			mAdapter.clear();
    		
        	if( backGroundThread == null ) {
        		backGroundThread = (BackGroundThread) new BackGroundThread();
        		backGroundThread.execute(false);
        	}
        	else {
        		switch(backGroundThread.getStatus()) {
	        		case PENDING :
	        		case RUNNING :
	        			backGroundThread.cancel(true);
	        		case FINISHED :
	        			backGroundThread = (BackGroundThread) new BackGroundThread();
	        			backGroundThread.execute(false);
	        			break;
        		}	
        	}
        }
    };

    private OnClickListener mSearchSelectClickListener = new OnClickListener() {
        public void onClick(View v) {
        	showDialog(RADIO_DIALOG);
        }
    };
	private AdapterView.OnItemClickListener mItemClickListener = new AdapterView.OnItemClickListener() {
		@Override
		public void onItemClick(AdapterView<?> arg0, View view, int position, long id) {
			switch( mAdapter.getItem(position).getType() ) {
				case ADD :
					mAdapter.removeLastItem();
					
		        	if( backGroundThread == null ) {
		        		backGroundThread = (BackGroundThread) new BackGroundThread();
		        		backGroundThread.execute(true);
		        	}
		        	else {
		        		switch(backGroundThread.getStatus()) {
			        		case PENDING :
			        		case RUNNING :
			        			backGroundThread.cancel(true);
			        		case FINISHED :
			        			backGroundThread = (BackGroundThread) new BackGroundThread();
			        			backGroundThread.execute(true);
			        			break;
		        		}	
		        	}
		        	break;
		        	
				case RESULT :
					sharedEditor.putInt("idx", mAdapter.getItem(position).getIdx());
					sharedEditor.commit();
	
					Intent startIntent  = new Intent(getBaseContext(), ResultActivity.class);
					startActivity(startIntent);
					break;
					
				case NOTFOUND :
				case PROGRESS :
					break;
			}
		}
	};
	
    private OnClickListener mHelpClickListener = new OnClickListener() {
        public void onClick(View v) {
			Intent startIntent  = new Intent(getBaseContext(), ResultActivity.class);
			startActivity(startIntent);
        }
    };
	
	
	
    // AsyncTask클래스는 항상 Subclassing 해서 사용 해야 함.
    // 사용 자료형은
    // background 작업에 사용할 data의 자료형: String 형
    // background 작업 진행 표시를 위해 사용할 인자: Integer형
    // background 작업의 결과를 표현할 자료형: Long
	private class BackGroundThread extends AsyncTask<Boolean, Integer, Integer> {
		private SearchResultData searchResultData;
		
    	// 이곳에 포함된 code는 AsyncTask가 execute 되자 마자 UI 스레드에서 실행됨.
    	// 작업 시작을 UI에 표현하거나
    	// background 작업을 위한 ProgressBar를 보여 주는 등의 코드를 작성.
		@Override
		protected void onPreExecute() {
			mAdapter.addItem(new WebViewContent(-1, "", SearchResultType.PROGRESS) );
			
			super.onPreExecute();
		}

		// UI 스레드에서 AsynchTask객체.execute(...) 명령으로 실행되는 callback 
		@Override
    	protected Integer doInBackground(Boolean... isNextSearch) {
           	int section = 1;
        	String gubun = "1";
    		
        	switch(type) {
	    		case IDIOM : // 관용
	    			gubun = String.valueOf(selectItem.getValue()+1);
	    			section = 1;
	    			break;
	    			
	        	case ADAGE : // 속담
	        		gubun = String.valueOf(selectItem.getValue()+1);
	        		section = 2;
	        		break;
	        		
	        	case DIALECT : // 방언 
	        		gubun = String.valueOf(selectItem.getValue());
	        		section = 3;
	        		break;
	        		
	        	case NKOREA : // 북한어
	        		gubun = String.valueOf(selectItem.getValue());
	        		section = 4;
	        		break;
	        		
	        	case NATIVE : // 고유어
	        		gubun = String.valueOf(selectItem.getValue());
	        		section = 5;
	        		break;
        	}
        	
        	try {
        		if(isNextSearch[0]) {
        			searchResultData = serviceConnection.getmService().sectionSearchNext(section);	
        		}
        		else {
        			searchResultData = serviceConnection.getmService().sectionSearch(editText.getText().toString(), section, gubun);
        		}
			} catch (RemoteException e) {
				e.printStackTrace();
			}
    		
    		return 1;
    	}
    	
    	// onInBackground(...)에서 publishProgress(...)를 사용하면
    	// 자동 호출되는 callback으로 이곳에서 ProgressBar를 증가 시키고, 
		// text 정보를 update하는 등의 background 작업 진행 상황을 UI에 표현함.
    	@Override
    	protected void onProgressUpdate(Integer... progress) {
    	}
    	
    	// onInBackground(...)가 완료되면 자동으로 실행되는 callback
    	@Override
    	protected void onPostExecute(Integer result) {
    		mAdapter.removeLastItem();
    		
    		ArrayList<WebViewContent> list = searchResultData.getWebViewContentList();    		
    		int size = searchResultData.getWebViewSize();
    		
    		if(size==0) {
    			mAdapter.addItem(new WebViewContent(-1, metaString+getString(R.string.not_found_string), SearchResultType.NOTFOUND));
    		}
    		else {
        		// mAdapter addItems
        		mAdapter.addItems(list);
            	
            	if( mAdapter.getCount()<size ) {
        			mAdapter.addItem(new WebViewContent(-1, metaString+getString(R.string.more_string), SearchResultType.ADD));
            	}
    		}
        	
        	Log.i("OtherActivity", "SIZE :" + size + "\nlist size :"+list.size()+"\nmAdapter size:"+mAdapter.getCount());
    	}
    	
    	// AsyncTask.cancel(boolean) 메소드가 true 인자로 
    	// 실행되면 호출되는 콜백.
    	// background 작업이 취소될때 꼭 해야될 작업은  여기에 구현.
    	@Override
		protected void onCancelled() {
			super.onCancelled();
		}  
	}
}